﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Threading;
using Twitterizer;
using System.Linq;

namespace KharaSoft.Nexus.Windows
{
    public partial class MainWindow
    {
        private readonly OAuthTokens _tokens = new OAuthTokens
                                          {
                                              AccessToken =
                                                  "14222410-H5dPQ0HI0RPyIQRIt4XQikVd3hTSi2HY7oRaBPnVL",
                                              AccessTokenSecret =
                                                  "juO05iHthTVKGtvw9gxH6WhWLbNuzZh2umzKwziRx0",
                                              ConsumerKey = "diO0K28Q1Q7LIiSzyPVqeA",
                                              ConsumerSecret =
                                                  "uwLQAiO51Du1AL7ZRUdjrFjWLcSisWE0Dy3WoNn6Fc"
                                          };

        private decimal _sinceStatusId;

        public MainWindow()
        {
            InitializeComponent();
            RefreshTimeline();
            InitializeMentions();
            InitializeDirectMessages();
            SetupTimer();
        }

        private void InitializeDirectMessages()
        {
            var receivedResponse = GetReceivedDirectMessages();
            var sentResponse = GetSentDirectMessages();
            if (sentResponse.Result == RequestResult.Success && receivedResponse.Result == RequestResult.Success)
            {
                UpdateDirectMessagesDisplay(sentResponse, receivedResponse);
            }
            else
            {
                MessageBox.Show(sentResponse.ErrorMessage);
            }
        }

        private void UpdateDirectMessagesDisplay(TwitterResponse<TwitterDirectMessageCollection> sentResponse, TwitterResponse<TwitterDirectMessageCollection> receivedResponse)
        {
            var dmReceived = receivedResponse.ResponseObject;
            var dmSent = sentResponse.ResponseObject;
            var directMessages = dmReceived.Union(dmSent).OrderByDescending(
                message => message.CreatedDate).Take(100);
            foreach (var message in directMessages)
            {
                Messages.Items.Add(message.Text);
            }
        }

        private TwitterResponse<TwitterDirectMessageCollection> GetReceivedDirectMessages()
        {
            return TwitterDirectMessage.
                DirectMessages(
                    _tokens,
                    new DirectMessagesOptions { Count = 100 });
        }

        private TwitterResponse<TwitterDirectMessageCollection> GetSentDirectMessages()
        {
            return TwitterDirectMessage
                .DirectMessagesSent(
                    _tokens,
                    new DirectMessagesSentOptions { Count = 100 });
        }

        private void InitializeMentions()
        {
            var mentionsResponse = GetMentions();
            if (mentionsResponse.Result == RequestResult.Success)
            {
                UpdateMentionsDisplay(mentionsResponse);
            }
            else
            {
                MessageBox.Show(mentionsResponse.ErrorMessage);
            }
        }

        private void UpdateMentionsDisplay(TwitterResponse<TwitterStatusCollection> mentionsResponse)
        {
            var mentions = mentionsResponse.ResponseObject;
            foreach (var tweet in mentions)
            {
                Mentions.Items.Add(tweet.Text);
            }
        }

        private TwitterResponse<TwitterStatusCollection> GetMentions()
        {
            return TwitterTimeline
                .Mentions(
                    _tokens,
                    new TimelineOptions { Count = 100 });
        }

        private void SetupTimer()
        {
            var timer = new DispatcherTimer(DispatcherPriority.Background,
                                            Dispatcher) { Interval = TimeSpan.FromMinutes(2) };
            timer.Tick += (s, e) => RefreshTimeline();
            timer.Start();
        }

        private void RefreshTimeline()
        {
            var timelineResponse =
                GetHomeTimeLineSince(_sinceStatusId);
            if (timelineResponse.Result ==
                RequestResult.Success)
            {
                var timeline = timelineResponse.ResponseObject;
                UpdateTimelineDisplay(timeline);
            }
            else
            {
                MessageBox.Show(
                    timelineResponse.ErrorMessage);
            }
        }

        private void UpdateTimelineDisplay(ICollection<TwitterStatus> timeline)
        {
            if (timeline == null) throw new ArgumentNullException("timeline");
            if (timeline.Count != 0)
                _sinceStatusId = timeline.First().Id;
            foreach (
                var tweet in timeline.Reverse())
            {
                Timeline.Items.Insert(0,
                                      tweet.Text);
            }
        }

        private TwitterResponse<TwitterStatusCollection> GetHomeTimeLineSince(decimal sinceStatusId)
        {
            return TwitterTimeline.HomeTimeline(_tokens,
                                                new TimelineOptions
                                                    {
                                                        Count = 100,
                                                        SinceStatusId =
                                                            sinceStatusId
                                                    });
        }
    }
}
